package com.isoft.c2team3service2.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.isoft.c2team3service2.bean.Userdetails;
import com.isoft.c2team3service2.entity.Role;
import com.isoft.c2team3service2.entity.User;
import com.isoft.c2team3service2.mapper.RoleMapper;
import com.isoft.c2team3service2.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userDao;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        // 1. 查询用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getEmail, email);
        User user = userDao.selectOne(wrapper);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 2. 查询用户角色
        List<Role> roleList = roleMapper.getRolesByUserId(user.getId());
        log.info("查询到的用户角色列表: {}", roleList);
        List<String> roles = roleList.stream()
                .map(Role::getName)
                .collect(Collectors.toList());
        List<SimpleGrantedAuthority> authorities = roles.stream()
                .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
                .collect(Collectors.toList());
        log.info("转换后的角色权限列表: {}", authorities);
        // 3. 封装为自定义UserDetails
        return new Userdetails(user, roles);
    }
}
